<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="queryTitle" placeholder="消息标题" style="width: 200px; margin:5px 5px 0 50;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="queryMobile" placeholder="接收消息的会员手机号" style="width: 200px; margin:5px 5px 0 0;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="queryNickname" placeholder="接收消息的会员昵称" style="width: 200px; margin:5px 5px 0 0;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-select v-model="queryStats" placeholder="状态" clearable style="width: 90px; margin:5px 5px 0 0;" class="filter-item">
        <el-option v-for="item in statsOptions" :key="item" :label="item" :value="item" />
      </el-select>
      <el-select v-model="queryIsPush" placeholder="推送" clearable style="width: 90px; margin:5px 5px 0 0;" class="filter-item">
        <el-option v-for="item in pushOption" :key="item" :label="item" :value="item" />
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter" />
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate" />
    </div>

    <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column label="消息标题" width="auto">
        <template slot-scope="scope">
          {{ scope.row.title }}
        </template>
      </el-table-column>
      <el-table-column label="消息类型" width="110" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.type | typeCssFilter">
            {{ row.type | typeFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="接收者" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.member_mobile }}
        </template>
      </el-table-column>
      <el-table-column label="消息状态" width="90" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.stats | statsCssFilter">
            {{ row.stats | statsFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="消息类型" width="110" align="center">
        <template slot-scope="{row}">
          <el-tag :type="row.is_push | pushCssFilter">
            {{ row.is_push | pushFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="消息发布者" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.created_by_name }}
        </template>
      </el-table-column>
      <el-table-column label="发布时间" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.created_at }}
        </template>
      </el-table-column>
      <el-table-column label="更新者" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.updated_by_name }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="110" align="center">
        <template slot-scope="scope">
          {{ scope.row.updated_at }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="{row, $index}">
          <el-button icon="el-icon-edit" type="primary" size="mini" @click="handleUpdate(row, $index)" />
          <el-button v-if="row.is_push === '1'" icon="el-icon-search" size="mini" @click="handlePushStatus(row, $index)" />
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="currentPage" :limit.sync="pageSize" @pagination="fetchData({})" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="70px" style="width: 400px; margin-left:50px;">
        <el-form-item label="消息标题">
          <el-input v-model="temp.title" />
        </el-form-item>
        <el-form-item label="消息类型">
          <el-radio-group v-model="temp.type" @change="handleMemberMobile">
            <el-radio label="0">系统消息</el-radio>
            <el-radio label="1">会员消息</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="showMobile === true" label="接收会员">
          <el-input v-model="temp.member_mobile" />
        </el-form-item>
        <el-form-item label="消息内容">
          <el-input v-model="temp.content" type="textarea" />
        </el-form-item>
        <el-form-item label="推送">
          <el-radio-group v-model="temp.is_push">
            <el-radio label="0">不推送</el-radio>
            <el-radio label="1">推送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="temp.stats">
            <el-radio label="0">禁用</el-radio>
            <el-radio label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create' ? createData() : updateData()">
          提交
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getList, createAnnounce, editAnnounce, deleteAnnounce, statsAnnounce } from '@/api/announce'
import Pagination from '@/components/Pagination'

export default {
  components: { Pagination },
  filters: {
    pushCssFilter(push) {
      const pushMap = {
        1: 'success',
        0: 'info'
      }
      return pushMap[push]
    },
    pushFilter(push) {
      const pushMap = {
        1: '推送',
        0: '不推送'
      }
      return pushMap[push]
    },
    typeCssFilter(type) {
      const typeMap = {
        1: 'success',
        0: 'danger'
      }
      return typeMap[type]
    },
    typeFilter(type) {
      const typeMap = {
        1: '会员消息',
        0: '系统消息'
      }
      return typeMap[type]
    },
    statsCssFilter(stats) {
      const statsMap = {
        1: 'success',
        0: 'danger'
      }
      return statsMap[stats]
    },
    statsFilter(stats) {
      const statsMap = {
        1: '显示',
        0: '不显示'
      }
      return statsMap[stats]
    }
  },
  data() {
    return {
      hidden: false,
      listLoading: true,
      // 翻页相关数据 当前页，每页显示条数，排序方式，排序字段，符合条件的搜索结果数，搜索结果
      currentPage: 1,
      pageSize: 10,
      sort: 'desc',
      order: 'id',
      total: 0,
      list: [],
      queryTitle: '',
      queryStats: '',
      queryIsPush: '',
      queryMobile: '',
      queryNickname: '',
      // 搜索条件相关数据
      statsOptions: ['不显示', '显示'],
      pushOption: ['不推送', '推送'],
      showReviewer: false,
      // 弹出层数据
      // 是否隐藏弹出层
      dialogFormVisible: false,
      // 弹出层状态(创建、编辑)
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      // 临时数据
      temp: {
        id: undefined,
        title: '',
        app_id: 0,
        content: 0,
        stats: 1
      },
      // 父级菜单
      appArr: [],
      rules: {
        name: [{ required: true, message: '菜单名称必须存在', trigger: 'change' }]
      },
      // 下载的loading
      downloadLoading: false,
      downloadData: [],
      // 是否显示输入会员手机号码的输入框
      showMobile: false
    }
  },
  mounted() {
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleFilter() {
      this.currentPage = 1
      this.fetchData()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        title: '',
        app_id: 0,
        content: 0,
        stats: 1
      }
    },
    handleMemberMobile(val) {
      console.log(typeof val)
      console.log(val === '1')
      if (val === '1') {
        this.showMobile = true
      } else {
        this.showMobile = false
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createAnnounce(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$notify({
              title: '创建成功',
              message: '菜单创建成功',
              type: 'success',
              duration: 2000
            })
            this.fetchData()
            this.dialogFormVisible = false
          }).catch(() => {
            this.$notify({
              title: '创建失败',
              type: 'error',
              message: '创建创建失败',
              duration: 2000
            })
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          editAnnounce(this.temp).then(response => {
            this.$notify({
              title: '编辑成功',
              type: 'success',
              message: '菜单编辑成功',
              duration: 2000
            })
            this.fetchData()
            this.dialogFormVisible = false
          }).catch(() => {
            this.$notify({
              title: '编辑失败',
              type: 'error',
              message: '菜单编辑失败',
              duration: 2000
            })
          })
        }
      })
    },
    formatJson(filterVal) {
    },
    handlePushStatus(row, idx) {
      statsAnnounce({ id: row.id }).then(resp => {
        const { data } = resp
        if (data === true) {
          this.$notify({
            title: '推送成功',
            message: '推送成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: '推送失败',
            message: '推送失败',
            type: 'error',
            duration: 2000
          })
        }
      }).catch(error => {
        console.log('error')
        console.log(error)
      })
    },
    handleUpdate(row, index) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true

      console.log(index)
      this.handleMemberMobile(this.temp.type)

      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleModifyStatus(row, value) {},
    handleDelete(row, idx) {
      const param = { id: row.id }
      deleteAnnounce(param).then(response => {
        this.$notify({
          title: '删除成功',
          message: '菜单删除成功',
          type: 'success',
          duration: 2000
        })
        this.fetchData()
        this.dialogFormVisible = false
      }).catch(() => {
        this.$notify({
          title: '删除失败',
          message: '菜单删除失败',
          type: 'error',
          duration: 2000
        })
      })
    },
    fetchData() {
      this.listLoading = true
      const param = {
        sort: this.sort,
        order: this.order,
        page: this.currentPage,
        page_size: this.pageSize
      }
      if (this.queryTitle !== '') {
        param.title = this.queryTitle
      }
      if (this.queryMobile !== '') {
        param.mobile = this.queryMobile
      }
      if (this.queryNickname !== '') {
        param.nickname = this.queryNickname
      }
      if (this.queryStats !== '') {
        this.statsOptions.map((item, idx) => {
          if (this.queryStats === item) {
            param.stats = idx
          }
        })
      }
      if (this.queryIsPush !== '') {
        this.pushOption.map((item, idx) => {
          if (this.queryIsPush === item) {
            param.is_push = idx
          }
        })
      }
      getList(param).then(response => {
        const { data, meta } = response
        this.list = data
        this.listLoading = false
        this.currentPage = parseInt(meta.current_page)
        this.total = parseInt(meta.total)
      }).catch(() => {
        this.listLoading = false
        this.list = []
      })
    }
  }
}
</script>
<style scoped>
  .filter-container {
    background: #fff;
    padding: 32px 16px;
  }
</style>
